package services

import (
	"errors"
	"fmt"
	"github.com/jassue/jassue-gin/app/common/request"
	"github.com/jassue/jassue-gin/app/models"
	"github.com/jassue/jassue-gin/global"
	"github.com/jassue/jassue-gin/utils"
	"gorm.io/gorm"
)

type roleService struct {
}

var RoleService = new(roleService)

// 添加角色
func (roleService *roleService) AddRole(params request.AddRole) (err error) {

	return global.App.DB.Transaction(func(db *gorm.DB) error {

		var result = db.Where("name = ?", params.Role_name).Select("id").First(&models.Role{})
		if result.RowsAffected != 0 {
			err = errors.New("角色名已存在")
			return err
		}

		role := models.Role{Name: params.Role_name}

		err = db.Create(&role).Error

		fmt.Println(role.ID.ID) //

		fmt.Printf("%+v\n", &role) //

		if len(params.Permissions) == 0 {
			return nil
		}

		//判断权限id是否存在 begin
		var Tmp []models.Permissions
		db.Select("id").Find(&Tmp, params.Permissions)

		fmt.Println("-----1Tmp  Permissions----")
		fmt.Printf("%+v\n", Tmp)

		//set := make(map[uint]struct{}, len(Roles))

		var slices []interface{}
		for _, v := range Tmp {
			slices = append(slices, v.ID.ID)
		}
		fmt.Printf("%+v\n", slices)

		for _, v := range params.Permissions {
			ok := utils.In_array(v, slices)
			if !ok {
				fmt.Printf("%+v\n", v) //
				err = errors.New("params.Permissions参数错误")
				db.Rollback()
				return err
			}
		}
		//判断权限id是否存在 end

		fmt.Println("-----1----")

		fmt.Printf("%+v\n", params.Permissions)

		// role_has_permissions 表添加数据
		TxErr := db.Delete(&[]models.RoleHasPermissions{}, "role_id = ?", role.ID.ID).Error
		if TxErr != nil {
			return TxErr
		}
		var role_permissions []models.RoleHasPermissions
		for _, v := range Tmp {
			role_permissions = append(role_permissions, models.RoleHasPermissions{
				Role_id: role.ID.ID, Permission_id: v.ID.ID,
			})
		}

		fmt.Printf("%+v\n", role_permissions)
		TxErr2 := db.Create(&role_permissions).Error

		if TxErr2 != nil {
			return TxErr2
		}

		//同时关联  casbin_rule  也插入同样的数据
		TxErrc := db.Delete(&[]models.Casbin_rule{}, "v0 = ?", utils.Int2string(role.ID.ID)).Error
		if TxErrc != nil {
			return TxErrc
		}
		var casbin_rules []models.Casbin_rule
		for _, v := range Tmp {
			casbin_rules = append(casbin_rules, models.Casbin_rule{
				Ptype: "p", V0: utils.Int2string(role.ID.ID), V1: utils.Int2string(v.ID.ID), V2: "post",
			})
		}

		fmt.Printf("%+v\n", casbin_rules)

		TxErr2c := db.Create(&casbin_rules).Error

		if TxErr2c != nil {
			return TxErr2c
		}

		// 返回 nil 提交事务

		return nil
	})

}

// 编辑角色
func (roleService *roleService) EditRole(params request.EditRole) (err error) {

	return global.App.DB.Transaction(func(db *gorm.DB) error {

		var result = db.Where("id<> ?  and name = ?", params.Role_id, params.Role_name).Select("id").First(&models.Role{})
		if result.RowsAffected != 0 {
			err = errors.New("角色名已存在")
			return err
		}

		role := models.Role{Name: params.Role_name}

		//编辑数据
		db.Model(&role).Where("id = ?", params.Role_id).Updates(&role)

		fmt.Println(role.ID.ID) //

		fmt.Printf("%+v\n", &role) //

		if len(params.Permissions) == 0 {
			// role_has_permissions 表添加数据
			TxErr := db.Delete(&[]models.RoleHasPermissions{}, "role_id = ?", params.Role_id).Error
			if TxErr != nil {
				return TxErr
			}
			//删除 casbin_rule
			TxErr2 := db.Delete(&[]models.Casbin_rule{}, "v0 = ?", params.Role_id).Error
			if TxErr2 != nil {
				return TxErr2
			}
			return nil
		} else {

			//判断权限id是否存在 begin
			var Tmp []models.Permissions
			db.Select("id").Find(&Tmp, params.Permissions)

			fmt.Println("-----1Tmp  Permissions----")
			fmt.Printf("%+v\n", Tmp)

			var slices []interface{}
			for _, v := range Tmp {
				slices = append(slices, v.ID.ID)
			}
			fmt.Printf("%+v\n", slices)

			for _, v := range params.Permissions {
				ok := utils.In_array(v, slices)
				if !ok {
					fmt.Printf("%+v\n", v) //
					err = errors.New("params.Permissions参数错误")
					db.Rollback()
					return err
				}
			}
			//判断权限id是否存在 end

			fmt.Println("-----1----")

			fmt.Printf("%+v\n", params.Permissions)

			// role_has_permissions 表添加数据
			TxErr := db.Delete(&[]models.RoleHasPermissions{}, "role_id = ?", params.Role_id).Error
			if TxErr != nil {
				return TxErr
			}
			var role_permissions []models.RoleHasPermissions
			for _, v := range Tmp {
				role_permissions = append(role_permissions, models.RoleHasPermissions{
					Role_id: params.Role_id, Permission_id: v.ID.ID,
				})
			}

			fmt.Printf("%+v\n", role_permissions)
			TxErr2 := db.Create(&role_permissions).Error

			if TxErr2 != nil {
				return TxErr2
			}

			//同时关联  casbin_rule  也插入同样的数据
			TxErrc := db.Delete(&[]models.Casbin_rule{}, "v0 = ?", utils.Int2string(params.Role_id)).Error
			if TxErrc != nil {
				return TxErrc
			}
			var casbin_rules []models.Casbin_rule
			for _, v := range Tmp {
				casbin_rules = append(casbin_rules, models.Casbin_rule{
					Ptype: "p", V0: utils.Int2string(params.Role_id), V1: utils.Int2string(v.ID.ID), V2: "post",
				})
			}

			fmt.Printf("%+v\n", casbin_rules)

			TxErr2c := db.Create(&casbin_rules).Error

			if TxErr2c != nil {
				return TxErr2c
			}

			// 返回 nil 提交事务
			return nil
		}
	})
}

// 角色列表
func (roleService *roleService) GetRoleList(params request.GetRoleList) (err error, result []*models.RoleList) {

	var page uint = params.Page - 1
	var keywords string = "%" + params.Keywords + "%"

	global.App.DB.Raw(" select roles.id as id,roles.name as role_name, group_concat( '',users.name) as user_names from roles "+
		" left join user_roles mhr on roles.id = mhr.role_id left join users"+
		" on mhr.model_id=users.id where roles.name like ? group by roles.id limit ?,?", keywords, page, params.Length).Scan(&result)

	return nil, result
}

// 删除角色
func (roleService *roleService) DelRole(params request.RoleId) (err error) {
	return global.App.DB.Transaction(func(db *gorm.DB) error {

		var result = db.Where("role_id= ? ", params.Role_id).Select("role_id").First(&models.UserRole{})
		if result.RowsAffected != 0 {
			err = errors.New("角色里还有用户，请先删除用户")
			return err
		}

		//

		TxErr := db.Delete(&[]models.RoleHasPermissions{}, "role_id = ?", params.Role_id).Error
		if TxErr != nil {
			return TxErr
		}
		//删除 casbin_rule
		TxErr2 := db.Delete(&[]models.Casbin_rule{}, "v0 = ?", utils.Int2string(params.Role_id)).Error
		if TxErr2 != nil {
			return TxErr2
		}

		TxErr3 := db.Delete(&[]models.Role{}, "id = ?", params.Role_id).Error
		if TxErr3 != nil {
			return TxErr3
		}
		return err
	})
}

// 获取角色内用户
func (roleService *roleService) GetRoleUsers(params request.RoleId) (err error, result []*models.RoleUsers) {

	global.App.DB.Raw(" select u.id as id,u.name as user_name,u.mobile,u.realname as real_name from "+
		"user_roles ur left join users u on u.id=ur.model_id  where ur.role_id=?", params.Role_id).Scan(&result)

	return nil, result
}

// 获取所有用户
func (roleService *roleService) GetAllUsers() (err error, result []*models.User) {

	global.App.DB.Raw(" select * from users where status=1").Scan(&result)

	return nil, result
}

// 保存组内用户 删除或添加用户
func (roleService *roleService) SaveRoleUsers(params request.SaveRoleUser) (err error) {
	return global.App.DB.Transaction(func(db *gorm.DB) error {

		//判断用户id是否存在 begin
		var Tmp []models.User
		db.Select("id").Find(&Tmp, params.Id_result)

		fmt.Println("-----1Tmp  Permissions----")
		fmt.Printf("%+v\n", Tmp)

		var slices []interface{}
		for _, v := range Tmp {
			slices = append(slices, v.ID.ID)
		}
		fmt.Printf("%+v\n", slices)

		for _, v := range params.Id_result {
			ok := utils.In_array(v, slices)
			if !ok {
				fmt.Printf("%+v\n", v) //
				err = errors.New("params.Id_result参数错误")
				db.Rollback()
				return err
			}
		}
		//判断用户id是否存在 end

		//删除user_roles
		TxErrc := db.Delete(&[]models.UserRole{}, "role_id = ?", params.Role_id).Error
		if TxErrc != nil {
			return TxErrc
		}

		if len(params.Id_result) == 0 {
			return nil
		} else {

			//添加数据 user_roles  params.Id_result
			var user_roles []models.UserRole
			for _, v := range Tmp {
				user_roles = append(user_roles, models.UserRole{
					UserId: v.ID.ID, RoleId: params.Role_id,
				})
			}

			fmt.Printf("%+v\n", user_roles)

			TxErr2c := db.Create(&user_roles).Error

			if TxErr2c != nil {
				return TxErr2c
			}
			return err
		}
	})
}

// 获取用户的角色
func (roleService *roleService) GetUserRoles(uid int) (err error, result []*models.UserRole) {

	global.App.DB.Raw(" select role_id from user_roles where model_id = ? ", uid).Scan(&result)

	return nil, result
}
